<template>
  <div class="classification-page">

    <el-table
        v-loading="tableLoading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="classifyId"
        :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        :tree-props="{ children: 'children' }"
        class="dataTable"
        default-expand-all
    >
      <el-table-column prop="classifyName" label="名称" width="300" />
      <el-table-column prop="classifyImage" label="图片">
        <template #default="scope">
          <el-image
              v-if="scope.row.classifyImage"
              :src="scope.row.classifyImage"
              style="width: 40px; height: 40px"
              fit="cover"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <!-- 二级分类显示"添加三级分类"按钮 -->
          <el-button
              v-if="scope.row.classifyLevel === 2"
              type="success"
              link
              @click.prevent="addThirdLevel(scope.row)"
          >
            添加三级分类
          </el-button>

          <!-- 三级分类显示"编辑"和"删除"按钮 -->
          <el-button
              v-if="scope.row.classifyLevel === 3"
              type="primary"
              link
              @click.prevent="editItem(scope.row)"
          >
            编辑
          </el-button>

          <el-popconfirm
              v-if="scope.row.classifyLevel === 3"
              title="确定要删除该分类吗？"
              @confirm="deleteItem(scope.row)"
          >
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑/新增弹窗 -->
    <EditDialog
        v-model:dialogVisible="dialogVisible"
        :params="dialogParams"
        :type="dialogParams.isAdd"
        @success="getClassTree"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {getCommodityClassTree, deleteCommodityClass, deleteCommodityClass1} from '@/api/commodityClassApi';
import EditDialog from './Edit.vue';

// 状态管理
const tableLoading = ref(false);
const tableData = ref<any[]>([]);
const dialogVisible = ref(false);
const dialogParams = ref({});
const formParams = reactive({
  page: 1,
  pageSize: 10,
});

// 初始化加载数据
onMounted(() => {
  getClassTree();
});

// 获取分类树形数据
const getClassTree = async () => {
  tableLoading.value = true;
  try {
    const res = await getCommodityClassTree(formParams);
    if (res.code === '200' && res.data) {
      // 处理数据格式，确保是数组
      tableData.value = Array.isArray(res.data) ? res.data : [res.data];
    } else {
      tableData.value = [];
      ElMessage.warning('未获取到分类数据');
    }
  } catch (error) {
    console.error('获取分类树失败:', error);
    ElMessage.error('获取数据失败，请重试');
    tableData.value = [];
  } finally {
    tableLoading.value = false;
  }
};

// 添加一级分类


// 添加三级分类（从二级分类操作）
const addThirdLevel = (row: any) => {
  dialogVisible.value = true;
  dialogParams.value = {
    parentId: row.classifyId,
    parentName: row.classifyName,
    level: 3,
    classifyLevel: 3,
    isAdd: true
  };
};

// 编辑分类（仅限三级）
const editItem = (row: any) => {
  dialogVisible.value = true;
  dialogParams.value = {
    ...row,
    id: row.classifyId,
    isAdd: false
  };
};

// 删除分类（仅限三级）
const deleteItem = async (row: any) => {
  try {
    const res = await deleteCommodityClass1({ oneClassifyId: row.classifyId });
    if (res.code === '200') {
      ElMessage.success('删除成功');
      getClassTree(); // 重新加载数据
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (error) {
    console.error('删除分类失败:', error);
    ElMessage.error('删除失败，请重试');
  }
};
</script>

<style lang="scss" scoped>
.classification-page {
  padding: 20px;
  background-color: #FFFFFF;
  .toolbar {
    margin-bottom: 15px;
    text-align: right;
  }
  .dataTable {
    margin-top: 10px;
  }
}
</style>
